﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
using System.Security.Cryptography;
using System.Web.Security;
using SQLExecute;

/// <summary>
/// Summary description for User
/// </summary>
public class User
{
    private int _id;
    private string _fullname;
    private string _username;
    private string _password;
    private string _email;
    private int _phongbanid;
    private int _groupid;
    public int PhongBanID
    {
        set { _phongbanid = value; }
        get { return _phongbanid; }
    }

    private string _tenphongban;
    public string TenPhongBan
    {
        set { _tenphongban = value; }
        get { return _tenphongban; }
    }

    public int GroupID
    {
        set { _groupid = value; }
        get { return _groupid; }
    }
    public DataSet Get_List_Users()
    {
        ds = SqlHelper.ExecuteDataset(Common.strConnect, "Get_List_Users");
        return ds;
    }

    public int ID
    {
        set { _id = value; }
        get { return _id; }
    }
    public string FullName
    {
        set { _fullname = value; }
        get { return _fullname; }
    }
    public string UserName
    {
        set { _username = value; }
        get { return _username; }
    }
    public string Password
    {
        set { _password = value; }
        get { return _password; }
    }
    public string Email
    {
        set { _email = value; }
        get { return _email; }
    }

	public User()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    private DataSet ds;
    public bool checkLogin(string u, string p)
    {

        ds = SqlHelper.ExecuteDataset(Common.strConnect, "Check_Login", new object[] { u, p });

        if (ds.Tables[0].Rows.Count > 0)
        {
            //this._id = Convert.ToInt16(ds.Tables[0].Rows[0]["id"].ToString());
            this._fullname = ds.Tables[0].Rows[0]["fullname"].ToString();
            this._username = ds.Tables[0].Rows[0]["username"].ToString();
            this._email = ds.Tables[0].Rows[0]["email"].ToString();
            this._tenphongban = ds.Tables[0].Rows[0]["phongban"].ToString();
            this._phongbanid = Convert.ToInt16(ds.Tables[0].Rows[0]["phongbanid"].ToString());
            if (ds.Tables[0].Rows[0]["groupid"] != null)
                this._groupid = Convert.ToInt16(ds.Tables[0].Rows[0]["groupid"].ToString());

            return true;
        }

        else return false;
    }
    public void Update_Password()
    {

        SqlHelper.ExecuteNonQuery(Common.strConnect, "Change_Pass", new object[] { _email, Encrypt_Pass() });

    }
    public string RandomPassword()
    {

        Guid id = new Guid();
        id = Guid.NewGuid();
        _password = id.ToString();
        _password = _password.Substring(0, 6);

        return _password;
    }
    public int Insert_New_User(string pass, bool active)
    {


        int i = SqlHelper.ExecuteNonQuery(Common.strConnect, "Insert_New_User"
                                          , new object[] { 
                                                          _fullname
                                                          ,_username
                                                          ,pass
                                                          ,_groupid
                                                          ,_phongbanid
                                                          , _email
                                                          , DateTime.Now.ToShortDateString()
                                                          , true });

        return i;
    }

    public int Insert_New_User(string strEncryptPassword)
    {


        int i = SqlHelper.ExecuteNonQuery(Common.strConnect, "Insert_New_User"
                                        , new object[] { _fullname
                                                        , _username
                                                        , strEncryptPassword
                                                        ,_groupid
                                                        ,_phongbanid
                                                        , _email                                                       
                                                        , DateTime.Now.ToShortDateString(), true });

        return i;
    }
    public string Encrypt_Pass()
    {

        UnicodeEncoding encoding = new UnicodeEncoding();
        Byte[] hashBytes = encoding.GetBytes(_password);
        // Compute the SHA-1  hash
        SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
        Byte[] cryptPassword = sha1.ComputeHash(hashBytes);

        return BitConverter.ToString(cryptPassword);

    }
    
    
    public void SendMail(string from, string to, string subject, int nCaseForSendMail)
    {

        string strMessageBody;
        string strLogo = string.Empty;
        AlternateView alternateView;
        StreamReader streamReader = null;

        //doc file template html
        if (nCaseForSendMail == 1)//new user
        {
            streamReader = new StreamReader(HttpContext.Current.Server.MapPath("~/template/mail_new_user.htm"));
            streamReader = File.OpenText(HttpContext.Current.Server.MapPath("~/template/mail_new_user.htm"));

        }
        else if (nCaseForSendMail == 2)//forgot password
        {
            streamReader = new StreamReader(HttpContext.Current.Server.MapPath("~/template/mail_forgot_password.htm"));
            streamReader = File.OpenText(HttpContext.Current.Server.MapPath("~/template/mail_forgot_password.htm"));

        }

        string strContentHtml = streamReader.ReadToEnd();
        streamReader.Close();

        //thay cac thong tin can thiet
        strMessageBody = strContentHtml.Replace("<Ten_Ung_Vien>", this._fullname);
        strMessageBody = strMessageBody.Replace("<username>", this._username);
        strMessageBody = strMessageBody.Replace("<password>", this._password);
        strMessageBody = strMessageBody.Replace("<image logo here>", "<img src=cid:imgLogo />");

        strLogo = HttpContext.Current.Server.MapPath(@"../images/logo.png");
        LinkedResource logo = new LinkedResource(strLogo);
        logo.ContentId = "imgLogo";
        ContentType mimeType = new System.Net.Mime.ContentType("text/html");
        alternateView = AlternateView.CreateAlternateViewFromString(strMessageBody, mimeType);

        alternateView.LinkedResources.Add(logo);

        System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(from, to);
        mailMessage.AlternateViews.Add(alternateView);
        mailMessage.Body = strMessageBody;

        mailMessage.IsBodyHtml = true;
        mailMessage.Subject = subject;
        SmtpClient s = new SmtpClient("192.168.0.100");
        s.Send(mailMessage);


    }
    public bool EmailExist()
    {
        string sql = "select fullname,username, email from tbl_users where email='" + _email + "'";
        SqlDataReader r;

        r = SqlHelper.ExecuteReader(Common.strConnect, CommandType.Text, sql);
        if (r.HasRows)
        {
            while (r.Read())
            {
                //_id = Convert.ToInt16(r[0].ToString());
                _fullname = r[0].ToString();
                _username = r[1].ToString();


            }

            r.Close();
            return true;
        }

        else

            return false;
    }
    public bool ValidMail(string s)
    {
        Regex regEmail = new Regex(@"^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
        if (regEmail.IsMatch(s))
            return true;
        else return false;
    }
}
